package com.uchengwang.ui.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.image.ImageManager;
import com.uchengwang.ui.base_ui.ui.MainActivity;
import com.uchengwang.ui.cm_ui.cycle.bean.CycleBean;
import com.uchengwang.ui.cm_ui.cycle.bean.RyGroupBean;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.login.ui.LoginActivity;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.cm_ui.ucity.ui.AppUpdateActivity;
import com.uchengwang.ui.cm_ui.uu.bean.CycleItemBean;
import com.uchengwang.ui.cm_ui.uu.bean.XiangliaoBean;
import com.uchengwang.ui.self.circledemo.bean.FavortItem;
import com.uchengwang.ui.self.circledemo.bean.User;
import com.uchengwang.ui.self.circledemo.widgets.PraiseListView;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by U城网 on 2017/5/10.
 */

public class DialogUtils {
    private AlertDialog dialog;
    private static DialogUtils utils;

    public static DialogUtils getUtils() {
        if (utils == null){
            utils = new DialogUtils();
        }
        return utils;
    }


    public AlertDialog showDialogSingle(Context context, boolean isCancle, String title, String content, String right, View.OnClickListener okOnClick){
        return showDialogAll(context, isCancle, title, content, "", right, okOnClick, null);
    }

    public AlertDialog showDialogSingle(Context context,  String content, String right, View.OnClickListener okOnClick){
        return showDialogAll(context, true, "", content, "取消", right, okOnClick, null);
    }

    public AlertDialog showDialogSingle(Context context,  String title, String content, String right, View.OnClickListener okOnClick){
        return showDialogAll(context, true, title, content, "取消", right, okOnClick, null);
    }

    /**
     * @param title 标题
     * @param content 内容
     * @param left 左边文字
     * @param right 右边文字
     * @param rightClick 右边文字点击事件
     * @param leftClick 取消点击事件
     * */

    public AlertDialog showDialogAll(Context context, boolean isCancle, String title, String content, String  left, String right, View.OnClickListener rightClick, View.OnClickListener leftClick) {//登录注册界面的dialog
        if (dialog != null && dialog.isShowing()){
            return dialog;
        }

        View view = View.inflate(context, R.layout.dialog_new, null);
        TextView dialog_title = (TextView) view.findViewById(R.id.dialog_title);
        TextView dialog_content = (TextView) view.findViewById(R.id.dialog_content);
        Button dialog_ok = (Button) view.findViewById(R.id.dialog_ok);
        Button dialog_cancel = (Button) view.findViewById(R.id.dialog_cancel);
        View dividerView = view.findViewById(R.id.dialog_divider);

        dialog_title.setText(title);
        dialog_content.setText(content);
        if (TextUtils.isEmpty(left)) {//只显示一个按钮
            dialog_cancel.setVisibility(View.GONE);
            dividerView.setVisibility(View.GONE);
        }else {
            dialog_cancel.setText(left);
        }

        dialog_ok.setText(right);
        if ( leftClick == null){
            dialog_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DialogUtils.getUtils().cancel();
                }
            });
        }else {
            dialog_cancel.setOnClickListener(leftClick);
        }
        dialog_ok.setOnClickListener(rightClick);

        dialog = initView(context, view, isCancle, null);
        return dialog;
    }


    /**
     * 享聊点击用户头像显示的界面
     * @param bean 用户信息
     * */
    public AlertDialog showXLDialog(final Context context, final XiangliaoBean bean, View.OnClickListener btListener, DialogInterface.OnDismissListener listener) {
        if (dialog != null && dialog.isShowing()){
            return dialog;
        }

        View view = View.inflate(context, R.layout.layout_xiangliao_dialog, null);
        LinearLayout xlDialog_cycle_item_ln = view.findViewById(R.id.xlDialog_cycle_item_ln);//共同社圈主题
        LinearLayout cycle_list_ln = view.findViewById(R.id.xlDialog_cycle_list_ln);
        LinearLayout friend_list_ln = view.findViewById(R.id.xlDialog_friend_list_ln);

        ImageView head = view.findViewById(R.id.xlDialog_head);
        TextView name =  view.findViewById(R.id.xlDialog_name);
        TextView school =  view.findViewById(R.id.xlDialog_school);

        Button bt =  view.findViewById(R.id.xlDialog_bt);
        bt.setOnClickListener(btListener);
        PraiseListView cycle_item_list = view.findViewById(R.id.xlDialog_cycle_item_list);
        PraiseListView cycle_list = view.findViewById(R.id.xlDialog_cycle_list);
        PraiseListView friend_list = view.findViewById(R.id.xlDialog_friend_list);

        List<CycleBean> cycleList = bean.getIntersectionCycles();
        List<UserBean> userList = bean.getIntersectionUsers();
        List<CycleItemBean> cycleItemBeans = bean.getIntersectionCycleItems();

        if (cycleItemBeans != null && cycleItemBeans.size() >0){
            List<FavortItem> cycles = new ArrayList<>();
            int len= (cycleItemBeans.size() >10 ? 10 :cycleItemBeans.size());
            for (int i=0; i<len; i++){
                FavortItem item = new FavortItem();
                User user = new User(cycleItemBeans.get(i).getId(), cycleItemBeans.get(i).getItemName(), cycleItemBeans.get(i).getCover());
                item.setUser(user);
                cycles.add(item);
            }
            cycle_item_list.setDatas(cycles);
        }else {
            xlDialog_cycle_item_ln.setVisibility(View.GONE);
        }


        if (cycleList != null && cycleList.size() >0){
            List<FavortItem> cycles = new ArrayList<>();
            int len= (cycleList.size() >10 ? 10 :cycleList.size());
            for (int i=0; i<len; i++){
                FavortItem item = new FavortItem();
                User user = new User(cycleList.get(i).getId(), cycleList.get(i).getCycleName(), cycleList.get(i).getCycleCover());
                item.setUser(user);
                cycles.add(item);
            }
            cycle_list.setDatas(cycles);
        }else {
            cycle_list_ln.setVisibility(View.GONE);
        }

        if (userList != null && userList.size() >0){
            List<FavortItem> users = new ArrayList<>();
            int len= (userList.size() >10 ? 10 :userList.size());
            for (int i=0; i<len; i++){
                FavortItem item = new FavortItem();
                if (userList.get(i) == null){
                    continue;
                }

                String nameString = "";
                if (!TextUtils.isEmpty(userList.get(i).getRemarkName())){
                    nameString = userList.get(i).getRemarkName();
                }else {
                    nameString = userList.get(i).getNickName();
                }
                User user = new User(userList.get(i).getId(), nameString, userList.get(i).getUserAvatar());
                item.setUser(user);
                users.add(item);
            }
            friend_list.setDatas(users);
        }else {
            friend_list_ln.setVisibility(View.GONE);
        }


        if (bean != null){
            ImageManager.getInstance().loadImage(context, head, bean.getUserAvatar(), ImageManager.ImageType.CIRCLE);
            if (!TextUtils.isEmpty(bean.getRemarkName())){
                name.setText(bean.getRemarkName());
            }else {
                name.setText(bean.getNickName());
            }
            school.setText(bean.getUniName());
        }

        dialog = initView(context, view, true, listener);
        return dialog;
    }


    /**
     * 判断是否登录 显示弹出框
     * */

    public void showLogin (final Activity activity){
        Intent intent = new Intent(activity, LoginActivity.class);
        if (activity instanceof MainActivity){
            //在主页跳转去登录, 在此登录重新打来
            intent.putExtra(BaseConfig.IS_TO_MAIN, true);
        }else {
            //登陆后还显示本页
            intent.putExtra(BaseConfig.IS_TO_MAIN, false);
        }
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.dd_y_menu_in, R.anim.dd_y_menu_out);
    }

    /**
     * 判断是否登录 显示弹出框
     * */

    public void showLogin (final Activity activity, boolean isAgainOpen){
        Intent intent = new Intent(activity, LoginActivity.class);
        //true在主页跳转去登录, 在此登录重新打来  false再次登录停留在打开界面
        intent.putExtra(BaseConfig.IS_TO_MAIN, isAgainOpen);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.dd_y_menu_in, R.anim.dd_y_menu_out);
    }

    /**
     * 申请加入群 先判断该群是否需要验证 不需要直接加入
     * @param isHide 是否隐藏加群按钮
     * */
    public AlertDialog  inviteGroup(final Context context, final RyGroupBean bean, boolean isHide, final OnResultListener listener){
        View view = View.inflate(context, R.layout.layout_add_group, null);
        final ImageView logo = (ImageView) view.findViewById(R.id.addGroup_logo);
        TextView name = (TextView) view.findViewById(R.id.addGroup_name);
        final TextView school = (TextView) view.findViewById(R.id.addGroup_school);
        TextView des = (TextView) view.findViewById(R.id.addGroup_des);

        if (bean.getUni() != null && !TextUtils.isEmpty(bean.getUni().getUniName())){
            school.setText(bean.getUni().getUniName());
        }else {
            school.setHint("暂无学校信息");
        }
        name.setText(bean.getGroupName());

        if (!TextUtils.isEmpty(bean.getGroupDesc())){
            des.setText(bean.getGroupDesc());
        }else {
            des.setHint("暂无群介绍");
        }
//        school.setText(bean);

        String logoUrl = bean.getGroupLogo();
        if (TextUtils.isEmpty(logoUrl)){
            ImageManager.getInstance().loadImage(context, logo, R.drawable.no_head, ImageManager.ImageType.CIRCLE);
        }else {
            ImageManager.getInstance().loadImage(context, logo, bean.getGroupLogo(), ImageManager.ImageType.CIRCLE);
        }

        Button join = (Button) view.findViewById(R.id.addGroup_join);

        if (!bean.isNeedApply()){
            join.setText("加入该群");
        }

        if (isHide){
            join.setVisibility(View.GONE);
        }

        join.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
                if (UCommonUtil.getUtil().isNeedLogin((Activity) context, false)){
                    return;
                }
                LoadingUtils.getUtils().loading(context);
                //做加群操作
                if (bean.isNeedApply()){
                    //需要验证
                    RyGroupManager.getManager().applyGroup((Activity) context, "申请加入您的群", bean.getId(),  bean.getGroupName(), new OnResultListener() {
                        @Override
                        public void onResult(int stutas, String msg, int total, String data) {
                            LoadingUtils.getUtils().hide();
                            if (stutas ==0){
                                UCommonUtil.getUtil().showToast(context, "请求发送成功");
                            }else {
                                UCommonUtil.getUtil().showToast(context, msg);
                            }
                            if (listener != null){
                                listener.onResult(stutas, msg, total, null);
                            }
                        }
                    });
                }else {
                    //不需要申请 直接加入
                    RyGroupManager.getManager().joinGroupNotApply((Activity) context, bean.getId(), new OnResultListener() {
                        @Override
                        public void onResult(int stutas, String msg, int total, String data) {
                            LoadingUtils.getUtils().hide();
                            if (stutas ==0){
                                UCommonUtil.getUtil().showToast(context, "加群成功");
                            }else {
                                UCommonUtil.getUtil().showToast(context, msg);
                            }
                            if (listener != null){
                                listener.onResult(stutas, msg, total, null);
                            }
                        }
                    });
                }

            }
        });

        dialog = initView(context, view, true, null);

        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();//得到这个dialog界面的参数对象
        params.width =WindowManager.LayoutParams.WRAP_CONTENT;//设置dialog的界面宽度
        params.height =  WindowManager.LayoutParams.WRAP_CONTENT;//设置dialog高度为包裹内容
        params.gravity = Gravity.CENTER;//设置dialog的重心
        dialog.getWindow().setAttributes(params);//最后把这个参数对象设置进去，即与dialog绑定
        return dialog;
    }


    /**
     * app更新提醒
     * */
    public AlertDialog appUpdate(final Context context, String title, String desc){
        return showDialogAll(context, false, title, desc, "在等等", "去更新", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到更新界面 加载一个网页
                cancel();

//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                Uri content_url = Uri.parse("http://uchengwang.com/ucwapi/download.jsp");
//                intent.setData(content_url);
//                context.startActivity(intent);

                context.startActivity(new Intent(context, AppUpdateActivity.class));

            }
        }, null);

    }

    /**
     * 弹出个窗 输入内容
     * @param title 显示的标题
     * @param maxLength 最长输入的字符数
     * @param content 显示上次输入的内容
     * */
    public void showEditWindow(final Context context, String title, String content, final int maxLength, final OnResultListener listener){
        View view = LayoutInflater.from(context).inflate(R.layout.layout_complete_data, null, false);
        TextView data_title =  view.findViewById(R.id.data_title);
        data_title.setText(title);
        final TextView data_num = view.findViewById(R.id.data_num);
        data_num.setText("0/"+maxLength);

        final EditText editText =  view.findViewById(R.id.data_group);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                data_num.setText(s.length() +"/" + maxLength);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        if (!TextUtils.isEmpty(content)){
            editText.setText(content);
        }


        Button cancel =  view.findViewById(R.id.data_cancel);
        Button data_sure =  view.findViewById(R.id.data_sure);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancel();
            }
        });
        data_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = editText.getText().toString();
                if (TextUtils.isEmpty(content)){
                    UCommonUtil.getUtil().showToast(context, "请输入");
                    return;
                }
                listener.onResult(0, "", 0, content);
                cancel();
            }
        });

        initView(context, view, true, null);
    }



    /**
     * @param isCancle 点击外面是否消失 true点击外面可以消失
     * */
    public AlertDialog initView(Context context, View view, boolean isCancle, DialogInterface.OnDismissListener onDismissListener){
        dialog = new AlertDialog.Builder(context, R.style.dialog).create();
        dialog.setCanceledOnTouchOutside(isCancle);
        if (onDismissListener == null){
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    DialogUtils.getUtils().cancel();
                }
            });
        }else {
            dialog.setOnDismissListener(onDismissListener);
        }


        view.setLayoutParams(new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        dialog.setView(view, 0, 0, 0, 0);

        dialog.show();
        return dialog;

    }




    public void cancel(){
        if (dialog != null && dialog.isShowing()){
            dialog.cancel();
        }
        if (utils != null){
            utils = null;
        }
    }




}
